"use client";

import { useState, useRef, useEffect } from "react";
import { Bot, Send, User } from "lucide-react";
import { Card, CardContent, CardFooter, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Separator } from "@/components/ui/separator";

type Message = {
  role: "user" | "assistant";
  content: string;
  timestamp: Date;
};

// Predefined responses for demo purposes
const PREDEFINED_RESPONSES: Record<string, string> = {
  "default": "I can help answer your questions about bgactor's AI solutions. Feel free to ask about our technology, use cases, or how we can help your business.",
  "hello": "Hello! I'm bgactor's AI assistant. How can I help you today?",
  "what can you do": "As bgactor's AI assistant, I can help with a variety of tasks including answering questions about our products, providing information about AI capabilities, helping with integration questions, and connecting you with our sales team for more specific inquiries.",
  "features": "bgactor offers several cutting-edge AI features: 1) Autonomous agents that adapt to your business needs, 2) Seamless enterprise integration with existing workflows, 3) Advanced analytics for operational insights, 4) Customizable AI behaviors, and 5) Robust security measures for enterprise data.",
  "pricing": "bgactor offers flexible pricing plans starting at $99/month for our basic package. For enterprise solutions with custom integrations, please contact our sales team for a personalized quote.",
  "integration": "bgactor's agents integrate seamlessly with most enterprise tools through our API. We offer pre-built connectors for popular services like Salesforce, Microsoft 365, Slack, and Google Workspace. Custom integrations are available for enterprise clients.",
  "security": "Security is our top priority. bgactor employs enterprise-grade encryption, regular security audits, and compliance with major regulations including GDPR, HIPAA, and SOC 2. All data processing follows strict privacy protocols."
};

// Helper function to get a response based on user input
function getAIResponse(message: string): string {
  message = message.toLowerCase().trim();
  
  // Check for key phrases and return appropriate response
  if (message.includes("hello") || message.includes("hi")) {
    return PREDEFINED_RESPONSES["hello"];
  }
  if (message.includes("what can you do") || message.includes("capabilities") || message.includes("help me")) {
    return PREDEFINED_RESPONSES["what can you do"];
  }
  if (message.includes("feature") || message.includes("ability") || message.includes("can do")) {
    return PREDEFINED_RESPONSES["features"];
  }
  if (message.includes("price") || message.includes("cost") || message.includes("pricing")) {
    return PREDEFINED_RESPONSES["pricing"];
  }
  if (message.includes("integrat") || message.includes("connect") || message.includes("api")) {
    return PREDEFINED_RESPONSES["integration"];
  }
  if (message.includes("security") || message.includes("privacy") || message.includes("safe")) {
    return PREDEFINED_RESPONSES["security"];
  }
  
  // Default response for any other query
  return PREDEFINED_RESPONSES["default"];
}

function formatTime(date: Date): string {
  return date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
}

export default function AIChatDemo() {
  const [input, setInput] = useState("");
  const [messages, setMessages] = useState<Message[]>([
    {
      role: "assistant",
      content: "Hi there! I'm bgactor's AI assistant. How can I help you today?",
      timestamp: new Date()
    }
  ]);
  const [isTyping, setIsTyping] = useState(false);
  const [isClient, setIsClient] = useState(false);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  
  // Set isClient to true once component is mounted
  useEffect(() => {
    setIsClient(true);
  }, []);
  
  // Auto-scroll to bottom when messages update
  useEffect(() => {
    messagesEndRef.current?.scrollIntoView({ behavior: "smooth" });
  }, [messages]);
  
  const handleSendMessage = () => {
    if (!input.trim()) return;
    
    // Add user message
    const userMessage: Message = {
      role: "user",
      content: input,
      timestamp: new Date()
    };
    
    setMessages(prev => [...prev, userMessage]);
    setInput("");
    setIsTyping(true);
    
    // Simulate AI response after a short delay
    setTimeout(() => {
      const aiResponse: Message = {
        role: "assistant",
        content: getAIResponse(userMessage.content),
        timestamp: new Date()
      };
      
      setMessages(prev => [...prev, aiResponse]);
      setIsTyping(false);
    }, 1000 + Math.random() * 1000); // Random delay between 1-2 seconds
  };
  
  return (
    <Card className="w-full max-w-4xl mx-auto border border-slate-800 bg-slate-900/50 backdrop-blur-sm">
      <CardHeader className="bg-slate-900 rounded-t-lg">
        <CardTitle className="flex items-center text-white">
          <Bot className="h-5 w-5 mr-2 text-[#50E3C2]" />
          bgactor AI Assistant
        </CardTitle>
      </CardHeader>
      <CardContent className="p-4 h-[400px] overflow-y-auto bg-slate-950/50">
        <div className="space-y-4">
          {messages.map((message, index) => (
            <div
              key={index}
              className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}
            >
              <div
                className={`flex items-start gap-2 max-w-[80%] ${
                  message.role === "user"
                    ? "bg-indigo-800/80 text-white"
                    : "bg-slate-800/80 text-zinc-100"
                } p-3 rounded-lg`}
              >
                {message.role === "assistant" && (
                  <Bot className="h-5 w-5 mt-1 text-[#50E3C2]" />
                )}
                <div>
                  <p className="text-sm">{message.content}</p>
                  <p className="text-xs opacity-60 mt-1">
                    {isClient ? formatTime(message.timestamp) : "Just now"}
                  </p>
                </div>
                {message.role === "user" && (
                  <User className="h-5 w-5 mt-1 text-white" />
                )}
              </div>
            </div>
          ))}
          {isTyping && (
            <div className="flex justify-start">
              <div className="bg-slate-800/80 text-zinc-100 p-3 rounded-lg flex items-center gap-2">
                <Bot className="h-5 w-5 text-[#50E3C2]" />
                <div className="typing-indicator">
                  <span className="dot"></span>
                  <span className="dot"></span>
                  <span className="dot"></span>
                </div>
              </div>
            </div>
          )}
          <div ref={messagesEndRef} />
        </div>
      </CardContent>
      <Separator className="bg-slate-800" />
      <CardFooter className="p-4 bg-slate-900 rounded-b-lg">
        <form
          className="flex items-center w-full gap-2"
          onSubmit={(e) => {
            e.preventDefault();
            handleSendMessage();
          }}
        >
          <Input
            placeholder="Ask about our AI solutions..."
            value={input}
            onChange={(e) => setInput(e.target.value)}
            className="flex-1 bg-slate-800 border-slate-700 text-white"
          />
          <Button
            type="submit"
            size="icon"
            variant="default"
            className="bg-[#50E3C2] hover:bg-[#3AC4A5] text-slate-950"
          >
            <Send className="h-4 w-4" />
          </Button>
        </form>
      </CardFooter>
    </Card>
  );
} 